<?php
require_once(DIR_LIBRARY."orm".DS."acl".DS."role.php");
require_once(DIR_LIBRARY."orm".DS."acl".DS."access.php");
require_once(DIR_LIBRARY."orm".DS."acl".DS."adminuser.php");

class AclPermission
{
    private static $mInstance;
    const DSN = "default";

	public static function isAllow($user_id, $access_id)
	{
        $admin_user = new AclAdminUser(); 
        $admin_user->loadByUserId($user_id);

        if (!$admin_user)
        {
            throw new Exception("no admin user");
        }

        $role_list = $admin_user->getField("role_list");

		if (!$role_list)
		{
			throw new Exception("user has no role ");
		}

		foreach ($role_list as $role_id)
		{
            $role = new AclRole($role_id);
			$access_list = self::buildListFromArray(array_values($role->getField("access_list")));
			$bool = self::inList($access_id, $access_list);

			if ($bool)
			{
				return true;
			}
		}

		return false;
	}

	public function getInstance()
	{
		if (!self::$mInstance)
		{
			$classname = __CLASS__;
			self::$mInstance = new $classname();
		}

		return self::$mInstance;
	}

	public static function resolveList($list)
	{
		$num = $list;
		$nums = array();

		while($num > 0)
		{
			$re = pow(2, floor(log($num, 2)));
			$num -= $re;
			$nums[] = (int)$re;
		}

		return $nums;
	}

	public static function inList($id, $id_list)
	{
		return (($id_list & $id) == $id) ? true : false;
	}

    public static function appendList($list, $item)
    {
        return $list + $item;
    }

    public static function buildListFromArray($arr)
    {
        if (!$arr || !is_array($arr))
        {
            throw new Exception("no array or  not array");
        }

        return array_sum($arr);
    }

} //end class
